package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.dto.UserThreadLocalUtil;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.minio.MinIOService;
import com.heima.media.dto.WmMaterialDto;
import com.heima.media.entity.WmMaterial;
import com.heima.media.mapper.WmMaterialMapper;
import com.heima.media.service.IWmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author Wq
 * @since 2022-10-09
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements IWmMaterialService {

    @Autowired
    private MinIOService minIOService;

    /**
     * 上传照片
     *
     * @param file 文件
     * @return {@code ResponseResult<WmMaterial>}
     */
    @Override
    public ResponseResult<WmMaterial> uploadPicture(MultipartFile file) {
        String url = minIOService.upload(file);
        //获取登录user
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //设置参数
        WmMaterial wmMaterial = new WmMaterial();
        // wmMaterial.setId();  主键自增
        wmMaterial.setUserId(user.getUserId());
        wmMaterial.setUrl(url);
        wmMaterial.setType(0);  //  0 图片  1 视频
        wmMaterial.setIsCollection(false);
        wmMaterial.setCreatedTime(new Date());
        this.save(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult showMaterialList(WmMaterialDto dto) {
        //1、获取当前登录用户
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2、执行查询
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        //3.1、根据登录用户id
        wrapper.eq(WmMaterial::getUserId, user.getUserId());
        //3.2、判断是否收藏
        Integer isCollection = dto.getIsCollection();
        if (isCollection != null) {
            wrapper.eq(WmMaterial::getIsCollection, isCollection);
        }
        //3.3排序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        //分页查询
        Page<WmMaterial> page = this.page(new Page<>(dto.getPage(), dto.getSize()), wrapper);
        //返回结果
        return new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
    }
}
